package com.rambo.sdh.common.service.impl;

import com.rambo.sdh.common.service.inter.GenCodeService;
import com.rambo.sdh.common.service.inter.vo.GenCodeTemplateVO;
import com.rambo.sdh.common.util.FreeMarkerUtil;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.io.resource.ResourceUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.xiaoleilu.hutool.xml.XstreamUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Create by Ramnbo on 2017/7/12
 **/
@Service
public class GenCodeServiceImpl implements GenCodeService {
    @Override
    public List<GenCodeTemplateVO> listGenCodeTemplateVO(List<String> templateNameList, Map<String, String> renderModel) {
        List<GenCodeTemplateVO> genCodeTemplateVOList = new ArrayList<>();
        try {
            String readString, renderString;
            for (String template : templateNameList) {
                readString = FileUtil.readString(ResourceUtil.getResource("template/" + template), "UTF-8");
                renderString = FreeMarkerUtil.renderString(readString, renderModel);
                genCodeTemplateVOList.add(XstreamUtil.xml2Vo(renderString, GenCodeTemplateVO.class));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return genCodeTemplateVOList;
    }

    @Override
    public String writeFile(List<GenCodeTemplateVO> codeTemplateVOList) {
        StringBuilder paths = new StringBuilder();
        paths.append("生成路径:\n");
        try {
            String path = ResourceUtil.getResource("/").getPath();
            String target = StrUtil.sub(path, 0, path.indexOf("target"));
            String normalizePath;
            for (GenCodeTemplateVO codeTemplateVO : codeTemplateVOList) {
                normalizePath = FileUtil.normalize(target + codeTemplateVO.getFilePath());
                FileUtil.writeUtf8String(codeTemplateVO.getContent(), normalizePath);
                paths.append(normalizePath);
                paths.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
        return paths.toString();
    }
}